package com.mogist.hqc.module.order.ui

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Intent
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import android.widget.TextView
import butterknife.OnClick
import butterknife.Optional
import com.mogist.hqc.R
import com.mogist.hqc.base.BaseMVPActivity
import com.mogist.hqc.entitys.BaseModel
import com.mogist.hqc.entitys.response.OrderVo
import com.mogist.hqc.module.order.contract.OrderDetailContract
import com.mogist.hqc.module.order.presenter.OrderDetailPresenter
import com.mogist.hqc.mvp.HttpDto
import com.mogist.hqc.util.Constant
import com.mogist.hqc.util.Util
import kotlinx.android.synthetic.main.activity_order_detail.*
import kotlinx.android.synthetic.main.include_title.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import talex.zsw.basecore.util.*
import talex.zsw.basecore.view.other.RxToast

/**
 * 作用：订单详情
 * 作者：赵小白 email:vvtale@gmail.com  
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
class OrderDetailActivity : BaseMVPActivity<OrderDetailContract.Presenter>(), OrderDetailContract.View
{
    private var orderNo = ""
    override fun initArgs(intent: Intent)
    {
        intent.getStringExtra("orderNo")
                ?.let {
                    orderNo = it
                }
    }

    override fun initView()
    {
        setContentView(R.layout.activity_order_detail)
        mPresenter = OrderDetailPresenter(this)
    }

    override fun initData()
    {
        mTitleBar.setTitle("订单详情")
        getData(false)
    }

    @Optional
    @OnClick(R.id.mTvCopy, R.id.mTvCancel, R.id.mTvPay, R.id.mTvComment, R.id.mTvRefund)
    fun onViewClicked(view: View)
    {
        if (!isFastClick)
        {
            when (view.id)
            {
                R.id.mTvCopy    ->
                { // 复制
                    ClipboardTool.copyText(this@OrderDetailActivity, orderNo)
                }
                R.id.mTvCancel  ->
                { //取消
                    errorTitle = "取消订单"
                    cancelOrder()
                }
                R.id.mTvRefund  ->
                { //退单
                    errorTitle = "退单"
                    cancelOrder()
                }
                R.id.mTvComment ->
                { //评论
                    showCommentDialog()
                }
                R.id.mTvPay     ->
                { //支付
                    val intent = Intent(this@OrderDetailActivity, OrderPayActivity::class.java)
                    intent.putExtra("order", detail!!)
                    start(intent)
                }
            }
        }
    }

    override fun getData(silence: Boolean)
    {
        val body = BaseModel(true)
        body.orderNo = orderNo
        mPresenter.getData(HttpDto(Constant.ORDER_DETAIL, body).setErrorTitle("获取订单详情失败").setType(
                HttpDto.GET).setFinish(true).setTryAgain(true))
    }

    var detail: OrderVo? = null
    @SuppressLint("SetTextI18n")
    override fun bindDetail(data: OrderVo)
    {
        detail = data
        // 订单信息
        mTvStatus.text = Util.getOrderStatus(data.orderStatus, data.payStatus)
        TextTool.getBuilder("￥")
                .append(data.amountAll)
                .setProportion(2F)
                .into(mTvPrice)
        if (RegTool.isEmpty(data.payType))
        {
            mTvPayType.text = "-"
        }
        else
        {
            mTvPayType.text = Util.getPayType(data.payType)
        }
        mTvOrderNo.text = data.orderNo
        mTvTime.text =
                TimeTool.changeFormat(data.createTime,
                                      "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
                                      TimeTool.STR_FOMATER_DATA_TIME)
        mTvMark.text = DataTool.getNotNull(data.remark, "-")
        // 产品信息
        mTvTitle.text = data.pdtName
        mTvInfo.text = "套餐类型：${data.proName}\n出发时间：${Util.getTimeStr(data.playDate)}"
        var contStr = ""
        if (data.amountAdult > 0)
        {
            contStr += data.amountAdult.toString() + "成人  "
        }
        if (data.amountChildren > 0)
        {
            contStr += data.amountAdult.toString() + "儿童"
        }
        mTvCount.text = contStr
        // 联系人信息
        mTvName.text = data.linkName
        mTvPhone.text = data.linkTel
        mTvEmail.text = data.email
        // 分别处理
        when (data.orderStatus)
        { // NEW("NEW", "新建订单"), FAILED("FAILED", "失效订单"), SUCCESS("SUCCESS", "成功订单"), FINISH("FINISH", "结束订单"), APPRAISED("APPRAISED", "已评价");
            "NEW"       ->
            { // 取消 支付
                mTvOverTime.visibility = View.VISIBLE
                mTvOverTime.text =
                        "请于 ${TimeTool.changeFormat(data.payOverTime,
                                                    "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
                                                    TimeTool.STR_FOMATER_DATA_TIME)} 前完成支付"
                mLLBottom.visibility = View.VISIBLE
                mTvCancel.visibility = View.VISIBLE
                mTvPay.visibility = View.VISIBLE
            }
            "FAILED"    ->
            {
            }
            "SUCCESS"   ->
            { // 退款
                mLLBottom.visibility = View.VISIBLE
                mTvRefund.visibility = View.VISIBLE
            }
            "FINISH"    ->
            { // 评论
                if ("PAYED" == data.payStatus)
                {
                    mLLBottom.visibility = View.VISIBLE
                    mTvComment.visibility = View.VISIBLE
                }
            }
            "APPRAISED" ->
            {
            }
            "REFUNDING" ->
            {
            }
        }
    }

    // --------------- 取消订单/退单 ---------------
    private var errorTitle = ""

    private fun cancelOrder()
    {
        val body = BaseModel(true)
        body.orderNo = orderNo
        mPresenter.getData(HttpDto(Constant.ORDER_CANCEL, body).setTryAgain(true).setErrorTitle(
                errorTitle + "失败"))
    }

    override fun cancelSuccess()
    {
        EventBus.getDefault().post(Constant.EVENT_REFRESH_ORDER)
        RxToast.success(errorTitle + "成功")
        mLLBottom.visibility = View.GONE
    }

    // --------------- 评论 ---------------
    private var dialog: Dialog? = null
    private var dEditText: EditText? = null
    private var commentStr = ""
    private fun showCommentDialog()
    {
        dialog
                ?: let {
                    dialog = Dialog(this@OrderDetailActivity, R.style.dialog)
                    dialog?.setContentView(R.layout.dialog_comment)
                    dialog?.setCanceledOnTouchOutside(true)
                    val display = window.windowManager.defaultDisplay
                    val layoutParams: WindowManager.LayoutParams = dialog?.window!!.attributes
                    layoutParams.width = (display.width * 1).toInt()
                    // layoutParams.height = (display.height * 0.8f).toInt()
                    layoutParams.gravity = Gravity.BOTTOM
                    if (layoutParams.gravity == Gravity.BOTTOM)
                    {
                        layoutParams.y = 0
                    }
                    dialog?.window!!.attributes = layoutParams

                    dEditText = dialog?.findViewById<EditText>(R.id.dEditText)
                    dialog?.findViewById<TextView>(R.id.dTvSure)
                            ?.setOnClickListener {
                                commentStr =
                                        dEditText!!.text.toString()
                                                .trim()
                                if (RegTool.isEmpty(commentStr))
                                {
                                    RxToast.warning("请输入评论信息")
                                }
                                else
                                {
                                    // 项目评论
                                    val body = BaseModel(true)
                                    body.orderNo = orderNo
                                    body.remark = commentStr
                                    mPresenter.getData(HttpDto(Constant.ORDER_COMMENT,
                                                               body).setErrorTitle("发表评论失败"))
                                }
                            }
                    dialog?.findViewById<TextView>(R.id.dTvCancel)
                            ?.setOnClickListener {
                                dialog?.dismiss()
                            }
                }
        dEditText?.setText("")
        KeyboardTool.showSoftInput(this@OrderDetailActivity,dEditText)
        dialog?.show()
    }

    override fun commentSuccess()
    {
        EventBus.getDefault().post(Constant.EVENT_REFRESH_ORDER)
        RxToast.success("评论成功")
        dialog?.dismiss()
        mLLBottom.visibility = View.GONE
    }

    // --------------- EventBus ---------------
    @Subscribe
    fun onEvent(event: String)
    {
        if (Constant.EVENT_PAY_SUCCESS == event)
        {
            finish()
        }
    }
}